package com.hhf.riceshopping.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.hhf.common.exception.NoStockException;
import com.hhf.common.to.mq.OrderTo;
import com.hhf.common.to.mq.SeckillOrderTo;
import com.hhf.common.utils.R;
import com.hhf.common.vo.MemberRespVo;
import com.hhf.riceshopping.order.constant.OrderConstant;

import com.hhf.riceshopping.order.entity.OrderItemEntity;
import com.hhf.riceshopping.order.entity.PaymentInfoEntity;
import com.hhf.riceshopping.order.enume.OrderStatusEnum;
import com.hhf.riceshopping.order.feign.CartFeignService;
import com.hhf.riceshopping.order.feign.MemberFeignService;
import com.hhf.riceshopping.order.feign.ProductFeignService;
import com.hhf.riceshopping.order.feign.WmsFeignService;
import com.hhf.riceshopping.order.interceptor.LoginUserInterceptor;
import com.hhf.riceshopping.order.service.OrderItemService;
import com.hhf.riceshopping.order.service.PaymentInfoService;
import com.hhf.riceshopping.order.to.OrderCreateTo;
import com.hhf.riceshopping.order.vo.*;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhf.common.utils.PageUtils;
import com.hhf.common.utils.Query;

import com.hhf.riceshopping.order.dao.OrderDao;
import com.hhf.riceshopping.order.entity.OrderEntity;
import com.hhf.riceshopping.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo> confirmVoThreadLocal = new ThreadLocal<OrderSubmitVo>();

    @Autowired
    PaymentInfoService paymentInfoService;

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    WmsFeignService wmsFeignService;



    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public PageUtils    queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    //给订单确认页返回需要用的数据
    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        //会员的id是登陆后的id，从登陆拦截器里面获取登陆后的会员用户id
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();//原来的请求

        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            //1.远程调用会员系统，并根据当前会员的id查询出保存的所有收获地址列表--ums_member_receive_address
            //每一个线程都来共享一下之前的请求数据
            RequestContextHolder.setRequestAttributes(requestAttributes);  //重新共享一下原来的请求
            List<MemberAddressVo> address = memberFeignService.getAddress(memberRespVo.getId());
            confirmVo.setAddress(address);
        }, executor);

        CompletableFuture<Void> CartFuture = CompletableFuture.runAsync(() -> {
            //2.远程查询购物车所有的选中的购物项 但这里没有传会员id，希望购物车服务能够自己获取登陆状态
            //每一个线程都来共享一下之前的请求数据
            RequestContextHolder.setRequestAttributes(requestAttributes);//重新共享一下原来的请求
            List<OrderItemVo> items = cartFeignService.getCurrentUserCartItems();
            confirmVo.setItems(items);

        }, executor).thenRunAsync(()->{
            //批量查询每一个商品的所有库存信息
            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> collect = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            //远程调用库存服务查询商品的库存信息
            R hasStock = wmsFeignService.getSkusHasStock(collect);
            //得到每一个商品库存的状态信息
            List<SkuStockVo> data = hasStock.getData(new TypeReference<List<SkuStockVo>>() {
            });
            if (data!=null){
                //map的key是商品id，v是是否有库存
                Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                confirmVo.setStocks(map);
            }
        },executor);


        //3.查询用户的积分信息
        confirmVo.setIntegration(memberRespVo.getIntegration());

        //4.其他比如订单总额自动计算好了


        //TODO 5.防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");  //令牌
        //防重令牌再放到redis当中 并且设置过期时间30分钟
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberRespVo.getId(),token,30, TimeUnit.MINUTES);
        //给页面设置一个令牌
        confirmVo.setOrderToken(token);
        CompletableFuture.allOf(getAddressFuture,CartFuture).get();

        return confirmVo;
    }

    /**
     * 下单操作逻辑
     * @param vo
     * @return
     */
    //@GlobalTransactional
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        confirmVoThreadLocal.set(vo);//把页面传来的所有数据都放到了threadlocal里边
        SubmitOrderResponseVo response = new SubmitOrderResponseVo();
        //会员的id是登陆后的id，从登陆拦截器里面获取登陆后的会员用户信息
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        response.setCode(0);
        //验证令牌是否合法，并且对比和删除令牌都必须是原子性
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        String orderToken = vo.getOrderToken();//从页面提交的令牌
        //原子验证和删除令牌操作
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()), orderToken);
        if (result==0L){
            //令牌验证失败
            response.setCode(1);
            return response;
        }else {
            //令牌验证成功 下单逻辑
            //创建订单以及订单项信息
            OrderCreateTo order = creataOrder();
            //验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();
           if (Math.abs(payAmount.subtract(payPrice).doubleValue())<0.01){
            //那么就验价对比成功 就把订单的所有数据保存到数据库
               saveOrder(order);
            //TODO 只要订单一保存成功，就立马进行库存锁定,防止订单支付以后，还没有库存  只要有异常就回滚整个订单数据，
            //给库存服务提供订单号，因为要给哪个订单锁的库存,还有所有的订单项（skuid，skunum,sku的名字）等
               WareSkuLockVo lockVo =new WareSkuLockVo();
               //设置库存锁定信息
               lockVo.setOrderSn(order.getOrder().getOrderSn());
               List<OrderItemVo> locks = order.getOrderItems().stream().map(item -> {
                   OrderItemVo itemVo = new OrderItemVo();
                   itemVo.setSkuId(item.getSkuId());
                   itemVo.setCount(item.getSkuQuantity());
                   itemVo.setTitle(item.getSkuName());
                   return itemVo;
               }).collect(Collectors.toList());
               lockVo.setLocks(locks);
               //远程锁库存
               //为了保证高并发，下订单成功之后，锁库存失败了可以发消息给库存服务
               //库存服务也可以本身使用解锁模式，这样下订单连消息都不用发了。无论是成了还是败了。库存都会进行自动解锁
               //如何自动解锁呢？使用消息队列来完成这个事情
               R r = wmsFeignService.orderLockStock(lockVo);
               if (r.getCode()==0){
                   //商品库存锁成功了
                   response.setOrder(order.getOrder());

//                   int i = 10/0;//模拟异常，订单回滚，库存不滚
                   //订单创建成功，就给MQ发送消息
                   rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order.getOrder());
                   return response;
               }else {
                   //商品库存锁失败了
                  // throw  NoStockException();
                   String msg = (String) r.get("msg");
//                   response.setCode(3);
//                   return response;
                   throw new NoStockException(msg);
               }
           }else {
               //对比失败
               response.setCode(2);  //金额对比失败
               return response;
           }

        }

    }

    /**
     *
     * @param orderSn  按照订单号获取订单状态信息
     * @return
     */
    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {

        return  baseMapper.selectOne(new QueryWrapper<OrderEntity>().eq("order_sn",orderSn));
    }

    /**
     * 关闭订单
     * @param entity
     */
    @Override
    public void closeOrder(OrderEntity entity) {
        //查询当期这个订单的最新状态
        OrderEntity orderEntity = this.getById(entity.getId());
        //什么情况下关单？是在待付款状态就需要关单,就去改状态
        if (orderEntity.getStatus() ==OrderStatusEnum.CREATE_NEW.getCode()){
            OrderEntity update = new OrderEntity();
            update.setId(entity.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            baseMapper.updateById(update);
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity,orderTo);
            try {
                //只要关单解锁成功，就立即再发订单信息发出去给MQ，告诉MQ，此次订单关单了。
                // 要保证消息能够百分之百发出去，每发一次消息也可以在数据库里边做好记录
                rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",orderTo);
            }catch (Exception e){
                //出现问题，就将没法发送成功的消息进行重试发送
            }


        }
    }

    /**
     *
     * @param orderSn 获取当期订单的所有支付信息
     * @return
     */
    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity order = this.getOrderByOrderSn(orderSn);
        //查询当期订单的所有订单项信息
        List<OrderItemEntity> order_sn = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity entity = order_sn.get(0);

        payVo.setBody(entity.getSkuAttrsVals());//订单备注
        payVo.setOut_trade_no(order.getOrderSn());//订单号
        payVo.setSubject(entity.getSkuName());//订单主题
        BigDecimal bigDecimal = order.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(bigDecimal.toString());//订单金额
        return payVo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id",memberRespVo.getId()).orderByDesc("id")
        );
        List<OrderEntity> order_sn = page.getRecords().stream().map(order -> {
            //吧每一个订单拿来再查询一下订单的订单项数据
            List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(itemEntities);
            return order;
        }).collect(Collectors.toList());
        page.setRecords(order_sn);
        return new PageUtils(page);
    }

    @Override
    public String handlePayResult(PayAsyncVo vo) {
        //保存交易流水信息
        PaymentInfoEntity infoEntity = new PaymentInfoEntity();
        infoEntity.setAlipayTradeNo(vo.getTrade_no());
        infoEntity.setOrderSn(vo.getOut_trade_no());
        infoEntity.setPaymentStatus(vo.getTrade_status());
        infoEntity.setCallbackTime(vo.getNotify_time());
        paymentInfoService.save(infoEntity);

        //修改订单支付后在订单列表页的状态信息
        if (vo.getTrade_status().equals("TRADE_SUCCESS") || vo.getTrade_status().equals("TRADE_FINISHED")){
            //支付成功状态
            String outTradeNo = vo.getOut_trade_no();
            //修改为已付款状态
           baseMapper.updateOrderStatus(outTradeNo,OrderStatusEnum.PAYED.getCode());
        }
        return "success";
    }

    @Override
    public void createSeckillOrder(SeckillOrderTo seckillOrder) {
            //保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(seckillOrder.getOrderSn());
        orderEntity.setMemberId(seckillOrder.getMemberId());

        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());

        BigDecimal multiply = seckillOrder.getSeckillPrice().multiply(new BigDecimal("" + seckillOrder.getNum()));
        orderEntity.setPayAmount(multiply);
        this.save(orderEntity);

        //TODO 保存订单项信息
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setOrderSn(seckillOrder.getOrderSn());
        orderItemEntity.setRealAmount(multiply);
        //TODO 获取当前SKU的详细信息进行设置  productFeignService.getSpuInfoBySkuId()
        orderItemEntity.setSkuQuantity(seckillOrder.getNum());

        orderItemService.save(orderItemEntity);
    }

    /**
     *
     * @param order 保存订单的所有数据
     */
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder(); //订单
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);
        List<OrderItemEntity> orderItems = order.getOrderItems();//订单项
        orderItemService.saveBatch(orderItems);

    }

    //创建订单
    private OrderCreateTo creataOrder(){
        OrderCreateTo createTo = new OrderCreateTo();
        //生成一个订单号
        String orderSn = IdWorker.getTimeId();
        //创建订单号
        OrderEntity orderEntity = buildOrder(orderSn);

        //获取到所有的订单项  直接从购物车服务里边进行获取
        List<OrderItemEntity> itemEntities = buildOrderItems(orderSn);

        //计算价格相关  要计算的是哪个订单，计算订单的所有订单项数据
        computePorice(orderEntity,itemEntities);
        createTo.setOrder(orderEntity);
        createTo.setOrderItems(itemEntities);
        return createTo;
    }

    /**
     * @param orderEntity 要计算的是哪个订单
     * @param itemEntities 计算订单的所有订单项数据
     */
    private void computePorice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {
        BigDecimal total = new BigDecimal("0.0");

        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");

        BigDecimal gift = new BigDecimal("0.0");
        BigDecimal growth = new BigDecimal("0.0");
        //订单价格相关的
        //订单总额  所有购物项相加后的结果
        for (OrderItemEntity entity : itemEntities) {
            //单价乘以数量
//            BigDecimal decimal = entity.getSkuPrice().multiply(new BigDecimal(entity.getSkuQuantity().toString()));//计算每一项的价格
            coupon = coupon.add(entity.getCouponAmount());
            integration = integration.add(entity.getIntegrationAmount());
            promotion = promotion.add(entity.getPromotionAmount());
            total = total.add(entity.getRealAmount());
            gift = gift.add(new BigDecimal(entity.getGiftIntegration().toString()));
//            Integer growth = entity.getGiftGrowth();
            growth = growth.add(new BigDecimal(entity.getGiftGrowth().toString()));
        }

        //1、订单价格相关
        orderEntity.setTotalAmount(total);
        //应付总额
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setCouponAmount(coupon);

        //设置积分等信息
        orderEntity.setIntegration(gift.intValue());
        orderEntity.setGrowth(growth.intValue());
        orderEntity.setDeleteStatus(0);//未删除

    }

    private OrderEntity buildOrder(String orderSn) {
        MemberRespVo respVo = LoginUserInterceptor.loginUser.get();//获取登陆的用户id
        OrderEntity entity = new OrderEntity();
        entity.setOrderSn(orderSn);//保存订单号
        entity.setMemberId(respVo.getId());
        //获取收货地址信息
        OrderSubmitVo submitVo = confirmVoThreadLocal.get();//获取从页面传递来的数据
        R fare = wmsFeignService.getFare(submitVo.getAddrId());//获取收货地址信息
        FareVo fareResp = fare.getData(new TypeReference<FareVo>() {
        });
        //设置运费
        entity.setFreightAmount(fareResp.getFare());
        //设置收货人信息
        entity.setReceiverCity(fareResp.getAddress().getCity());
        entity.setReceiverDetailAddress(fareResp.getAddress().getDetailAddress());
        entity.setReceiverName(fareResp.getAddress().getName());
        entity.setReceiverPhone(fareResp.getAddress().getPhone());
        entity.setReceiverPostCode(fareResp.getAddress().getPostCode());
        entity.setReceiverProvince(fareResp.getAddress().getProvince());
        entity.setReceiverRegion(fareResp.getAddress().getRegion());

        //设置订单状态
        //设置订单的相关状态信息
        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        entity.setAutoConfirmDay(7);

        return entity;
    }


    /**
     * 构建所有订单项数据
     * @param orderSn  为哪个订单号构建的订单项
     * @return
     */
    private List<OrderItemEntity> buildOrderItems( String orderSn) {
        List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();//获取当前用户的购物车数据
        if (currentUserCartItems!=null && currentUserCartItems.size() > 0) {
            List<OrderItemEntity> itemEntities = currentUserCartItems.stream().map(cartItem -> {
                //构建每一个的订单项信息,并返回订单项的信息
                OrderItemEntity itemEntity =  buildOrderItem(cartItem);
                itemEntity.setOrderSn(orderSn);

                return itemEntity;
            }).collect(Collectors.toList());
            return itemEntities;
        }
        return null;
    }

    /**
     * 构建某一个订单项数据
     * @param cartItem
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity itemEntity = new OrderItemEntity();
        //构建每一个订单项
        //订单信息：订单号标识是哪个订单的 完成
        //商品的spu的信息
        Long skuId = cartItem.getSkuId();
        //利用skuid去远程调用商品服务查询商品spu的信息
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo data = r.getData(new TypeReference<SpuInfoVo>() {
        });
        itemEntity.setSpuId(data.getId());
        //TODO 可以去远程查询商品服务的品牌信息并设置进去
        itemEntity.setSpuBrand(data.getBrandId().toString());
        itemEntity.setSpuName(data.getSpuName());
        itemEntity.setCategoryId(data.getCatalogId());

        //商品的sku的信息
        itemEntity.setSkuId(cartItem.getSkuId());
        itemEntity.setSkuName(cartItem.getTitle());
        itemEntity.setSkuPic(cartItem.getImage());
        itemEntity.setSkuPrice(cartItem.getPrice());
        //collectionToDelimitedString可以用数组转成String
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuQuantity(cartItem.getCount());
        //积分信息
        itemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        itemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());

        //订单项的价格信息
        itemEntity.setPromotionAmount(new BigDecimal("0"));
        itemEntity.setCouponAmount(new BigDecimal("0"));
        itemEntity.setIntegrationAmount(new BigDecimal("0"));
        //当前订单项的实际金额。 总额-各种优惠
        BigDecimal orign = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()));
        BigDecimal subtract = orign.subtract(itemEntity.getCouponAmount())
                .subtract(itemEntity.getPromotionAmount())
                .subtract(itemEntity.getIntegrationAmount());
        itemEntity.setRealAmount(subtract);
        return itemEntity;
    }

}